/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package grest.controller;

import grest.model.DataIO;
import grest.view.FormMozos;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

/**
 *
 * @author Agustin
 */
public class CntrlrFocusFieldsMozos implements FocusListener {
    FormMozos form;
    
    public CntrlrFocusFieldsMozos(FormMozos form){
        this.form= form;
    }
    @Override
    public void focusGained(FocusEvent e) {
    }

    @Override
    public void focusLost(FocusEvent e) {
        if(e.getSource()==form.getControls("txtID")){
            if(((JTextField) form.getControls("txtID")).getText().length()>0)
                try{
                    this.setDataProducto(Integer.parseInt(((JTextField)form.getControls("txtID")).getText()));
                }catch(NumberFormatException ex){
                    JOptionPane.showMessageDialog(this.form,"Entrada no válida", "Error",JOptionPane.ERROR_MESSAGE);
                    ((JButton)form.getControls("btnGuardar")).setEnabled(false);
                }
            else{
                
            }
        }
    }
    
    
    public void setDataProducto(Integer nroProducto){
        boolean existe=false;
        String consulta = "select id_producto,descripcion,precio_base from t_productos where id_producto = "+ nroProducto;
        ResultSet rs = DataIO.getResultSet(consulta);
       if ( rs != null ){                   
            try {
                while ( rs.next() ) {
                    Integer precio = rs.getInt("precio_base");
                    ((JTextField)form.getControls("txtPrecio")).setText(precio.toString());
                    ((JLabel)form.getControls("lblDescripcion")).setText(rs.getString("descripcion"));
                    existe=true;
                }
                if(!existe)((JLabel)form.getControls("lblDescripcion")).setText("Producto inexistente"); 
                 ((JButton)form.getControls("btnGuardar")).setEnabled(existe);
            } catch (SQLException sql) {
                DataIO.doException(sql,"Error loading objects from ["+consulta+"]");
            }
       }
       else{
           ((JLabel)form.getControls("lblDescripcion")).setText("Se ha producido un error"); 
           ((JButton)form.getControls("btnGuardar")).setEnabled(false);
       }
       
    }
}